import React, { useEffect, useState } from 'react';
import { Layout, Menu } from 'antd';
import { Application } from '../core';
import { ModelStore, ViewFactory } from '../model';
import { 
  AppstoreOutlined, 
  ShoppingCartOutlined, 
  UserOutlined, 
  TeamOutlined, 
  SettingOutlined, 
  FileOutlined, 
  ShopOutlined, 
  DashboardOutlined 
} from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { mockNavigation } from '../mock';
import './Navigation.less';

const { Sider } = Layout;
type MenuItem = Required<MenuProps>['items'][number];

// Navigation item interfaces
interface NavigationMenuItem {
  id: string;
  displayName: string;
  viewName: string;
}

interface NavigationGroup {
  id: string;
  displayName: string;
  icon?: string;
  items?: NavigationMenuItem[];
}

interface NavigationStructure {
  items: NavigationGroup[];
}

/**
 * Navigation Component - Displays the application navigation structure
 */
const Navigation: React.FC = () => {
  const app = Application.getInstance();
  const modelStore = ModelStore.getInstance();
  const viewFactory = ViewFactory.getInstance();
  const [navigationData, setNavigationData] = useState<NavigationStructure | null>(null);
  
  useEffect(() => {
    // Get navigation data from model store or use mock data as fallback
    const navFromStore = modelStore.navigation as NavigationStructure;
    
    if (navFromStore && navFromStore.items && navFromStore.items.length > 0) {
      console.log('Navigation: Using navigation data from ModelStore', navFromStore);
      setNavigationData(navFromStore);
    } else {
      console.log('Navigation: Using mock navigation data', mockNavigation);
      setNavigationData(mockNavigation);
    }
  }, []);

  // Debug the navigation data
  console.log('Navigation component rendering with data:', navigationData);

  // Handle menu item click
  const handleMenuClick = (viewName: string) => {
    console.log(`Navigation: handleMenuClick called for viewName=${viewName}`);
    
    // Create the view from factory
    const view = viewFactory.createView(viewName);
    console.log(`Navigation: viewFactory.createView returned:`, view);
    
    if (!view) {
      console.error(`Failed to create view: ${viewName}`);
      return;
    }
    
    // Navigate to the view
    if (app.activeWindow) {
      console.log(`Navigation: navigating to view ${view.name} in window ${app.activeWindow.id}`);
      try {
        app.activeWindow.navigate(view);
        console.log(`Navigation: navigation successful`);
      } catch (error) {
        console.error(`Navigation failed:`, error);
      }
    } else {
      console.error(`Cannot navigate: no active window`);
    }
  };

  // Map icon name to component
  const getIcon = (iconName?: string) => {
    switch (iconName) {
      case 'shopping-cart':
        return <ShoppingCartOutlined />;
      case 'appstore':
        return <AppstoreOutlined />;
      case 'user':
        return <UserOutlined />;
      case 'team':
        return <TeamOutlined />;
      case 'setting':
        return <SettingOutlined />;
      case 'file':
        return <FileOutlined />;
      case 'shop':
        return <ShopOutlined />;
      case 'dashboard':
        return <DashboardOutlined />;
      default:
        return <AppstoreOutlined />;
    }
  };

  // Convert navigation items to Ant Design menu items
  const getMenuItems = (): MenuItem[] => {
    if (!navigationData || !navigationData.items) {
      console.warn('No navigation data available');
      return [];
    }

    return navigationData.items.map((group: NavigationGroup) => {
      // Create submenu items
      const children = group.items?.map((item: NavigationMenuItem) => ({
        key: item.id,
        label: item.displayName,
        onClick: () => handleMenuClick(item.viewName)
      }));

      // Create menu group
      return {
        key: group.id,
        icon: getIcon(group.icon),
        label: group.displayName,
        children
      };
    });
  };

  return (
    <Sider width={200} className="mini-xaf-navigation" theme="light">
      <div className="logo-container" style={{ height: 64, padding: '16px', textAlign: 'center' }}>
        <h3 style={{ margin: 0 }}>Mini XAF</h3>
      </div>
      <Menu
        mode="inline"
        style={{ height: '100%', borderRight: 0 }}
        items={getMenuItems()}
        defaultOpenKeys={navigationData?.items?.map((i: NavigationGroup) => i.id) || []}
      />
    </Sider>
  );
};

export default Navigation;
